<template>
  <!-- 视频预览区域 -->
  <video ref="videoRef" autoplay playsinline></video>
  <!-- 操作按钮 -->
  <button @click="startCamera">开启摄像头</button>
  <button @click="stopCamera">关闭摄像头</button>
  <button @click="capturePhoto">拍照</button>
  <button @click="startRecording">视频录制</button>
  <button @click="stopRecording">关闭视频录制</button>
  <button @click="switchCamera">切换摄像头</button>
  <!-- 照片预览 -->
  <canvas ref="canvasRef"></canvas>
</template>

<script setup>
import { ref, onBeforeUnmount } from 'vue';

const videoRef = ref(null);
const canvasRef = ref(null);
let mediaStream = null; // 存储摄像头流

// 启动摄像头
const startCamera = async () => {
  try {
    // 请求摄像头权限
    mediaStream = await navigator.mediaDevices.getUserMedia({
      video: {
        width: 1280,   // 分辨率宽度
        height: 720,   // 分辨率高度
        facingMode: 'user' // 前置摄像头，'environment'为后置
      },
      audio: true
    });
    
    // 将视频流绑定到video元素
    if (videoRef.value) {
      videoRef.value.srcObject = mediaStream;
    }
  } catch (error) {
    handleCameraError(error);
  }
};

// 拍照功能
const capturePhoto = () => {
  const canvas = canvasRef.value;
  const video = videoRef.value;
  
  if (!canvas || !video) return;

  const ctx = canvas.getContext('2d');
  // 设置画布尺寸与视频一致
  canvas.width = video.videoWidth;
  canvas.height = video.videoHeight;
  
  // 绘制当前帧
  ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
  
  // 获取Base64图片数据
  const imageData = canvas.toDataURL('image/png');
  console.log('照片数据:', imageData);
};

// 关闭摄像头
const stopCamera = () => {
  if (mediaStream) {
    mediaStream.getTracks().forEach(track => track.stop());
    mediaStream = null;
  }
};

// 错误处理
const handleCameraError = (error) => {
  console.error('摄像头错误:', error);
  let msg = '';
  switch(error.name) {
    case 'NotAllowedError':
      msg = '用户拒绝了权限请求';
      break;
    case 'NotFoundError':
      msg = '未找到摄像头设备';
      break;
    default:
      msg = '未知错误';
  }
  alert(`摄像头错误: ${msg}`);
};

// 组件卸载时自动关闭摄像头
onBeforeUnmount(() => {
  stopCamera();
});

let mediaRecorder = null;
let recordedChunks = [];

const startRecording = () => {
    console.log('开始录制视频...');                      // 添加日志记录
  if (!mediaStream) return;

  mediaRecorder = new MediaRecorder(mediaStream);
  
  mediaRecorder.ondataavailable = (event) => {
    if (event.data.size > 0) {
      recordedChunks.push(event.data);
    }
  };
  
  mediaRecorder.onstop = () => {
    const videoBlob = new Blob(recordedChunks, { type: 'video/webm' });
    const videoUrl = URL.createObjectURL(videoBlob);
    // 生成可下载链接
    const a = document.createElement('a');
    a.href = videoUrl;
    a.download = 'recording.webm';
    a.click();
  };
  
  mediaRecorder.start();
};

const stopRecording = () => {
  console.log('停止录制视频...');                      // 添加日志记录
  if (mediaRecorder) {
    mediaRecorder.stop();
  }
};

const switchCamera = async () => {
  const devices = await navigator.mediaDevices.enumerateDevices();
  const videoDevices = devices.filter(d => d.kind === 'videoinput');
  
  if (videoDevices.length < 2) {
    alert('未找到多个摄像头设备');
    return;
  }
  
  // 获取当前摄像头ID
  const currentDeviceId = mediaStream.getVideoTracks()[0].getSettings().deviceId;
  
  // 选择下一个设备
  const newDevice = videoDevices.find(d => d.deviceId !== currentDeviceId);
  
  // 重新初始化摄像头
  stopCamera();
  mediaStream = await navigator.mediaDevices.getUserMedia({
    video: {
      deviceId: { exact: newDevice.deviceId },
      width: 1280,
      height: 720
    }
  });
  videoRef.value.srcObject = mediaStream;
};
</script>